using UnityEngine;

namespace BehaviorDesigner.Runtime.Tasks
{
    [TaskDescription("Attack the enemy.")]
    [TaskCategory("Custom")]
    public class ActionAttack : Action
    {
        [Tooltip("The enemy to attack")]
        public Transform enemy;
        [Tooltip("The interval of attacking")]
        public float attackTime = 1f;

        private EnemyManager _enemyManager;
        private Animator _roleAnimator;
        private float _attackCounter = 0f;

        public override void OnAwake()
        {
            _roleAnimator = transform.GetChild(0).GetComponent<Animator>();
            _enemyManager = enemy.GetComponent<EnemyManager>();
        }

        public override TaskStatus OnUpdate()
        {
            if (Blackboard.isEnemyDead)
            {
                _PlayIdle();
                return TaskStatus.Failure;
            }

            _attackCounter += Time.deltaTime;
            if (_attackCounter >= attackTime)
            {
                bool isDead = _enemyManager.TakeHit();
                if (isDead)
                {
                    Blackboard.isEnemyDead = isDead;
                    _PlayIdle();
                    return TaskStatus.Success;
                }
                else
                {
                    _attackCounter = 0f;
                }
            }

            _PlayAttack();
            return TaskStatus.Running;
        }

        private void _PlayIdle()
        {
            _roleAnimator.SetBool("Idle", true);
            _roleAnimator.SetBool("Attack", false);
        }

        private void _PlayAttack()
        {
            _roleAnimator.SetBool("Idle", false);
            _roleAnimator.SetBool("Attack", true);
        }
    }
}